package indi.henry.demo.exception;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import lombok.extern.slf4j.Slf4j;

/**
 * Exception handling for the application
 * 
 * @author Henry Hu
 */
@Slf4j
@RestControllerAdvice
public class ExceptionHandlers {

    @ExceptionHandler(IOException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String exceptionHandler(IOException e, HttpServletRequest request) {
        log.error("IO Exception message: {}", e.getMessage());
        return e.getMessage();
    }

    @ExceptionHandler(BadRequestException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String exceptionHandler(BadRequestException e, HttpServletRequest request) {
        log.error("BadRequestException message: {}", e.getMessage());
        return e.getMessage();
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String exceptionHandler(IllegalArgumentException e, HttpServletRequest request) {
        log.error("IllegalArgumentException message: {}", e.getMessage());
        return e.getMessage();
    }

    @ExceptionHandler(NotFoundException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String exceptionHandler(NotFoundException e, HttpServletRequest request) {
        log.error("NotFoundException message: {}", e.getMessage());
        return e.getMessage();
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String ioExceptionHandler(ConstraintViolationException e, HttpServletRequest request) {
        log.error("ConstraintViolationException message: {}", e.getMessage());
        return e.getMessage();
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
    public String exceptionHandler(RuntimeException e, HttpServletRequest request) {
        log.error("Runtime Exception message: {}", e.getMessage());
        return e.getMessage();
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String exceptionHandler(Exception e, HttpServletRequest request) {
        log.error("Unknown Exception message: {}", e.getMessage());
        return e.getMessage();
    }
}
